<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    :minHeight="300"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <FormTitle text="基础设置" class="pl-4" />
    <BasicForm class="mt-2" @register="registerForm" @field-value-change="handleChangeFeild">
      <template #helpMessage="{ model, field }">
        <div
          ><a-textarea :rows="1" v-model:value="model[field]" placeholder="请输入说明/帮助" />
          <Checkbox v-model:checked="helpBefore">名称前 </Checkbox>
          <Checkbox v-model:checked="helpAfter">名称后 </Checkbox></div
        >
      </template>
    </BasicForm>
    <template v-if="RELA_FIELD_TYPE.includes(fieldType)">
      <FormTitle text="关联表设置" class="ml-4" />
      <div class="mt-2">
        <BasicForm @register="registerRelaForm" />
      </div>
    </template>
    <div class="my-4" v-if="OPTIONS_FIELD_TYPE.includes(fieldType)">
      <FormTitle text="选项设置" class="ml-4" />

      <CommonConfig
        class="pl-9"
        :data="searchOptions"
        :columns="tableColumns"
        @add="handleAddCustomOption()"
        @del="handleUpdateItem"
        @del-mutil="handleUpdateList"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import CommonConfig from './CommonConfig.vue';
  import FormTitle from './FormTitle.vue';
  import { titlesSchema, relaTableSchema, classificationColumns } from './title.data';
  import { LIST_FIELD_TYPE, SEARCH_TYPE } from '/@/components/ModelTable/src/types';

  import { Checkbox } from 'ant-design-vue';
  // import { ApiSelect } from '/@/components/Form';
  import { cloneDeep } from 'lodash-es';
  import { DICT } from '/@/enums/dict';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDictTypeListApi } from '/@/api/admin/dict';

  const RELA_FIELD_TYPE = [LIST_FIELD_TYPE.RELA_FIELD_TYPE, LIST_FIELD_TYPE.SUB_FIELD_TYPE];
  const OPTIONS_FIELD_TYPE = [
    LIST_FIELD_TYPE.OPTION_FIELD_TYPE,
    LIST_FIELD_TYPE.MIX_FIELD_TYPE,
    LIST_FIELD_TYPE.IMG_FIELD_TYPE,
    LIST_FIELD_TYPE.LINK_FIELD_TYPE,
  ];

  export default defineComponent({
    name: 'TableTitleConfigModal',
    components: { BasicModal, BasicForm, CommonConfig, FormTitle, Checkbox },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const updateInfo = ref<any>({
        isUpdate: false,
      });

      const { createMessage } = useMessage();

      const searchType = ref();
      const fieldType = ref();
      const searchOptions = ref<any>([]);
      const helpBefore = ref(false);
      const helpAfter = ref(false);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 160,
        baseColProps: { lg: 12, md: 24 },
        schemas: titlesSchema,
        showActionButtonGroup: false,
      });

      const [registerRelaForm, { setFieldsValue: setRelaFields, validate: relaValid }] = useForm({
        labelWidth: 160,
        baseColProps: { lg: 12, md: 24 },
        schemas: relaTableSchema,
        showActionButtonGroup: false,
      });

      async function init(data: Indexable) {
        searchType.value = '';
        fieldType.value = '';
        updateInfo.value = {
          isUpdate: !!data?.isUpdate,
          index: data?.record?.index,
          record: cloneDeep(data?.record || {}),
        };
        if (!!data?.isUpdate) {
          setFieldsValue({
            ...data?.record,
          });
          helpBefore.value = data?.record.helpBefore;
          helpAfter.value = data?.record.helpAfter;

          searchType.value = data?.record.searchType;
          fieldType.value = data?.record.fieldType;

          if (data?.record.relaTableInfo) {
            nextTick(() => {
              setRelaFields(data?.record.relaTableInfo);
            });
          }
        }
        tableColumns.value = await classificationColumns(unref(fieldType));
        searchOptions.value = data?.record.displayCondition || [];
      }

      const tableColumns = ref<any[]>([]);
      const [registerDrawer, { setModalProps, closeModal, scrollBottom }] = useModalInner(
        async (data: Indexable) => {
          resetFields();
          setModalProps({ confirmLoading: false });

          init(data);
        },
      );

      const getTitle = computed(() => (!unref(updateInfo).isUpdate ? '新增' : '编辑'));

      async function handleChangeFeild(key, val) {
        switch (key) {
          case 'searchType':
            searchType.value = val;
            break;
          case 'fieldType':
            fieldType.value = val;
            if (OPTIONS_FIELD_TYPE.includes(val)) {
              tableColumns.value = await classificationColumns(unref(fieldType));
            }
            break;

          default:
            break;
        }
      }
      function handleChangeSearch(v) {
        console.log(
          '%cv===>95： ',
          'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
          v,
        );
      }
      // scrollTop
      async function modelScroll() {
        setTimeout(async () => {
          scrollBottom && (await scrollBottom());
        }, 100);
      }
      const handleAddCustomOption = () => {
        const optionItem = {
          field: '',
          op: '=',
          label: '',
          value: '',
          labelType: undefined,
        };
        searchOptions.value.push(optionItem);
        modelScroll();
      };
      const handleUpdateItem = (idx) => {
        searchOptions.value.splice(idx, 1);
      };
      const handleUpdateList = (arr) => {
        searchOptions.value = arr || [];
      };
      async function handleSubmit() {
        try {
          const values = await validate();
          values.helpBefore = helpBefore.value;
          values.helpAfter = helpAfter.value;

          setModalProps({ confirmLoading: true });

          // 字段类型配置
          const fType = unref(fieldType);
          if (RELA_FIELD_TYPE.includes(fType)) {
            const relaTableInfo = await relaValid();
            values.relaTableInfo = relaTableInfo;
          }

          // 分类值等字段配置
          if (OPTIONS_FIELD_TYPE.includes(fType)) {
            let options = unref(searchOptions);
            values.displayCondition = options;
          }

          const params = Object.assign(unref(updateInfo).record, values);

          createMessage.success('操作成功', 0.8);
          closeModal();
          updateInfo.value.record = params;
          emit('success', updateInfo.value);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      function handleCancel() {
        //  重置数据
        updateInfo.value.isUpdate && emit('success', unref(updateInfo));
      }

      return {
        DICT,
        SEARCH_TYPE,
        getTitle,
        fieldType,
        RELA_FIELD_TYPE,
        searchType,
        searchOptions,
        tableColumns,
        OPTIONS_FIELD_TYPE,
        helpBefore,
        helpAfter,
        handleCancel,
        registerDrawer,
        registerForm,
        handleSubmit,
        handleChangeFeild,
        handleChangeSearch,
        getDictTypeListApi,
        handleAddCustomOption,
        handleUpdateList,
        registerRelaForm,
        handleUpdateItem,
      };
    },
  });
</script>
